package com.dhcc.android.base.common.view.AutoCompleteTextView;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AutoCompleteTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 公共的dialog
 */
public class InitAutoCompleteUtil {

	/**
	 * 初始化AutoCompleteTextView，最多显示5项提示，使 AutoCompleteTextView在一开始获得焦点时自动提示
	 */
	public static void initAutoComplete(Context context, String field,
			MyAutoCompleteTextView auto) {
		AutoCompleteAdapter adapter;
		SharedPreferences sp = context.getSharedPreferences("network_url", 0);
		String longhistory = sp.getString(field, "nothing");
		String[] hisArrays = longhistory.split(",");
		List<String> hisArraysList = new ArrayList<String>();
		for (String t : hisArrays) {
			hisArraysList.add(t);
		}
		adapter = new AutoCompleteAdapter(context, hisArraysList, 10);

		// 只保留最近的20条的记录
		if (hisArrays.length > 20) {
			String[] newArrays = new String[20];
			System.arraycopy(hisArrays, 0, newArrays, 0, 20);

			List<String> newArraysList = new ArrayList<String>();
			for (String t : newArrays) {
				newArraysList.add(t);
			}
			adapter = new AutoCompleteAdapter(context, newArraysList, 10);
		}
		auto.setAdapter(adapter);
		// auto.setDropDownHeight(180);
		auto.setThreshold(0);

		// auto.setCompletionHint("最近的5条记录");
		auto.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				AutoCompleteTextView view = (AutoCompleteTextView) v;
				if (hasFocus) {
					view.showDropDown();
				}
			}
		});
	}

	/**
	 * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
	 */
	public static void saveHistory(Context context, String field, String text) {
		SharedPreferences sp = context.getSharedPreferences("network_url", 0);
		String longhistory = sp.getString(field, "nothing");
		if (!longhistory.contains(text + ",")) {
			StringBuilder sb = new StringBuilder(longhistory);
			sb.insert(0, text + ",");
			sp.edit().putString(field, sb.toString()).commit();
		}
	}

	/**
	 * 指定AutoCompleteTextView中内容删除sharedPreference中指定的字符段
	 */
	public static void deleteHistory(Context context, String field, String text) {
		SharedPreferences sp = context.getSharedPreferences("network_url", 0);
		String longhistory = sp.getString(field, "nothing");
		longhistory = longhistory.replace(text, "");
		longhistory = longhistory.replace(",,", ",");
		sp.edit().putString(field, longhistory).commit();
	}
}
